package com.utilcase.rabbitmq;

import cn.hutool.core.util.RandomUtil;
import com.utilcase.domain.MessageLog;
import com.utilcase.enums.MessageStatus;
import com.utilcase.service.MessageLogService;
import com.utilcase.service.OrdersService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

/**
 * 生产消息
 *
 * @author yoo
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class MessageProducer {
    private final RabbitTemplate rabbitTemplate;
    private final MessageLogService messageLogService;
    private final OrdersService ordersService;

    public void sendMsg(String exchange, String routingKey, String body) {
        // 生成唯一的消息ID  (orderId)
        String messageId = String.valueOf(ordersService.createOrder());
        // 记录消息到数据库
        MessageLog message = new MessageLog();
        message.setMessageId(messageId);
        // 随机生成消息内容
        String randomStr = RandomUtil.randomString("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 10);
        message.setPayload(randomStr);
        message.setStatus(MessageStatus.PENDING);
        message.setExchange(exchange);
        message.setRoutingKey(routingKey);
        messageLogService.save(message);
        //创建CorrelationData对象，包含唯一id,id的作用是在回调函数中识别消息，也就是根据id跟踪这条消息
        CorrelationData correlationData = new CorrelationData("orderId_" + messageId);
        // 基于路由模式发送消息到RabbitMQ
        rabbitTemplate.convertAndSend(exchange, routingKey, message, msg -> {
            //自定义消息属性或者头信息
            MessageProperties properties = msg.getMessageProperties();
            properties.setMessageId(messageId);//唯一消息ID
            properties.setDeliveryTag(1);
            properties.setConsumerTag(messageId);//自定义tag
            // 自定义消息头信息
//            properties.setHeaders(new HashMap<>());
//            properties.setHeader(AmqpHeaders.CONSUMER_TAG, deliveryTag);
            // 获取消息的属性，设置传输模式DeliveryMode为持久化，会写入磁盘
//            properties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
            //消息过期时间 5秒
//            properties.setExpiration("5000");
            log.info("发送消息：{}，messageId:{}", msg, messageId);
            return msg;
        }, correlationData);
    }
}